﻿using System;

namespace KinectWS
{
    /// <summary>
    /// Simple Echo WebSocket Server
    /// </summary>
    public class EchoWebSocket : IDisposable
    {
        int port;
        SuperWebSocket.WebSocketServer wsServer;

        public event Action<string> OnMessage;

        public EchoWebSocket(int port)
        {
            this.port = port;
        }


        /// <summary>
        /// Run Server
        /// </summary>
        public void Conect()
        {
            var rootConfig = new SuperSocket.SocketBase.Config.RootConfig();
            var serverConfig = new SuperSocket.SocketBase.Config.ServerConfig()
            {
                Port = this.port,
                Ip = "Any",
                MaxConnectionNumber = 100,
                Mode = SuperSocket.SocketBase.SocketMode.Sync,
                Name = "Ms Innovation Server"
            };

            wsServer = new SuperWebSocket.WebSocketServer();
            wsServer.Setup(rootConfig, serverConfig, SuperSocket.SocketEngine.SocketServerFactory.Instance);

            wsServer.NewSessionConnected += HandleServerNewSettionConnected;
            wsServer.NewMessageReceived += HansdleServerNewMessageReceived;
            wsServer.SessionClosed += HandleServerSessionClosed;

            Console.WriteLine("start");
            wsServer.Start();
        }

        /// <summary>
        /// Dispose Server
        /// </summary>
        public void Dispose()
        {
            wsServer.Dispose();
        }

        /// <summary>
        /// Send WebSocket Message to All clients
        /// </summary>
        /// <param name="msg">the message</param>
        public void SendToAllSession(string msg)
        {
            var sessions = wsServer.GetAllSessions();
            foreach (var session in sessions)
            {
                session.SendResponse(msg);
            }
            this.OnMessage(msg);
        }

        void HandleServerNewSettionConnected(SuperWebSocket.WebSocketSession session)
        {
            Console.WriteLine("connected");
            session.SendResponse("hello");
        }

        void HansdleServerNewMessageReceived(SuperWebSocket.WebSocketSession session, string e)
        {
            Console.WriteLine("received:" + e);
            this.OnMessage(e);
            SendToAllSession(e);
        }

        void HandleServerSessionClosed(SuperWebSocket.WebSocketSession session, SuperSocket.SocketBase.CloseReason e)
        {
            Console.WriteLine("closed");
        }

    }
}
